package admin;

import java.io.File;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.time.Clock;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import Tool.Properties_tool;

public class User_photo_cache extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		JSONObject jsonObj = new JSONObject();
		
		try {
			String url = Data_entry.class.getResource("/admin/system_set.properties").toURI().getPath();
			Properties_tool pp = new Properties_tool(url);
			String ip = pp.getvalue("ip");
			Clock clock = Clock.systemUTC();
			String cache_photo_id = String.valueOf((int)(Math.random()*900000)+100000)+clock.millis();  //缓存图片编号
			
			String photo_url = "http://"+ip+"/tmpfs/auto.jpg?" + clock.millis();
			System.out.println(photo_url);
			
			URL p_url = new URL(photo_url);	
			HttpURLConnection conn = (HttpURLConnection) p_url.openConnection();  //获取连接
			
			int status;
			if((status = conn.getResponseCode())==200){  //链接成功
				FileInputStream in = (FileInputStream)conn.getInputStream();   //获取字节输入流
				//InputStreamReader c_in = new InputStreamReader(in,"UTF-8");    //转换为字符流
				
				File file = new File(request.getServletContext().getRealPath("/img_cache")+"/"+cache_photo_id+".jpg");
				
				System.out.print(request.getServletContext().getRealPath("/img_cache")+"/"+cache_photo_id+".jpg");
				
				FileOutputStream file_out = new FileOutputStream(file);
				byte[] b = new byte[1024];
				int len = 0;
				while((len = in.read(b))!=-1){
					file_out.write(b, 0, len);
				}
				
				in.close();
				file_out.close();
				jsonObj.put("result", true);
			}else{
				//失败
				System.out.print("失败"+status);
				jsonObj.put("result", false);
			}
		} catch (URISyntaxException e) {
			jsonObj.put("result", false);
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		out.print(jsonObj.toString());
	}

}
